package com.xy.ahoy.navigation

import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.animation.core.tween
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.xy.ahoy.ui.launcher.LauncherBody
import com.xy.compose.login.navigation.loginScreen
import com.xy.compose.main.navigation.mainScreen
import com.xy.compose.nav.AppNavigator
import com.xy.compose.nav.handleNavigationEvent
import com.xy.compose.nav.routes.MainRouter
import kotlinx.coroutines.flow.collectLatest

@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
fun AppNavHost(
    navigator: AppNavigator,
    modifier: Modifier = Modifier
) {
    val navController = rememberNavController()
    // 监听导航事件
    LaunchedEffect(navController) {
        navigator.navigationEvents.collectLatest { event ->
            navController.handleNavigationEvent(event)
        }
    }
    SharedTransitionLayout {
        NavHost(
            navController = navController,
            MainRouter.LAUNCHER_PAGE,
            modifier,
            // 页面进入动画
            enterTransition = {
                slideIntoContainer(
                    AnimatedContentTransitionScope.SlideDirection.Left,
                    animationSpec = tween(300)
                )
            },
            // 返回时页面进入动画
            popEnterTransition = {
                slideIntoContainer(
                    AnimatedContentTransitionScope.SlideDirection.Right,
                    animationSpec = tween(300)
                )
            },
            // 返回时页面退出动画
            popExitTransition = {
                slideOutOfContainer(
                    AnimatedContentTransitionScope.SlideDirection.Right,
                    animationSpec = tween(300)
                )
            }
        ) {
            // 启动页面
            composable(MainRouter.LAUNCHER_PAGE) { LauncherBody(navController) }
            //登录页面
            loginScreen()
            //主页面
            mainScreen()
        }

    }
}
